import re
from flask import request
from flask_shop.user import user,user_api
from flask_shop import models,db
from flask_restful import Resource,reqparse
from flask_shop.utils.message import to_dict_msg
from flask_shop.utils.tokens import generate_auth_token,verify_auth_token,login_required
from flask_cors import *




@user.route('/')
def index():
    return "User Hello"


class User(Resource):
    def get(self):
        try:
            id = int(request.args.get("id").strip())
            usr = models.User.query.filter_by(id = id).first()
            if usr:
                return to_dict_msg(200,usr.to_dict(),"获取用户成功！")
            else:
                return to_dict_msg(200,[],'没有该用户！')
        except Exception as e:
            return to_dict_msg(10000)

    def post(self):
        # 创建用户 user/user/
        name = request.form.get('name')
        pwd = request.form.get('pwd')
        real_pwd = request.form.get('real_pwd')
        nick_name = request.form.get("nick_name")
        phone = request.form.get("phone")
        email = request.form.get("email")

        if not all([name,pwd,real_pwd]):
            return to_dict_msg(10000)

        if len(name) < 2:
            return to_dict_msg(10011)
        
        if len(pwd) < 2:
            return to_dict_msg(10011)

        if pwd != real_pwd:
            return to_dict_msg(10012)

        if not re.match(r'1[345678]\d{9}$',phone):
            return to_dict_msg(10013)
        
        if not re.match(r"^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$",email):
            return to_dict_msg(10014)
        try:
            rid = request.form.get("role_name").strip()  if request.form.get("role_name") else 0
            usr = models.User(name = name, password = pwd, nick_name = nick_name, phone = phone, email = email, rid = rid)
            # 提交事务
            db.session.add(usr)
            db.session.commit()
            return to_dict_msg(200)
        except Exception as e:
            print(e)
            return to_dict_msg(400)
    
    def put(self):
        # 修改用户
        try:
            id = int(request.form.get("id").strip())
            nick_name = request.form.get("nick_name").strip() if request.form.get("nick_name") else ""
            email = request.form.get("email").strip()  if request.form.get("email") else ""
            phone = request.form.get("phone").strip()  if request.form.get("phone") else ""
            rid = request.form.get("role_name").strip()  if request.form.get("role_name") else 0
            
            usr =  models.User.query.get(id)
            if usr :
                usr.nick_name = nick_name
                usr.email = email
                usr.phone = phone
                usr.rid = rid
                db.session.commit()
                return to_dict_msg(200,msg="修改数据成功")
            else:
                return to_dict_msg(10017)
        except Exception as e:
            print(e)
            return to_dict_msg(10000)
    def delete(self):
        # 删除用户
        try:
            id = request.json.get("id")
            usr = models.User.query.get(id)
            if usr:
                db.session.delete(usr)
                db.session.commit()
                return to_dict_msg(200,msg="删除成功")
            else:
                return to_dict_msg(10018)
        except Exception as e:
            print(e)
            return to_dict_msg(400)

user_api.add_resource(User,"/user/")


class UserList(Resource):
    # 查询参数
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument("name",type=str)
        parser.add_argument("pnum",type=int)
        parser.add_argument("psize",type=int)
        try:
            args = parser.parse_args()
            name = args.get("name")
            pnum = args.get('pnum') if args.get("pnum") else 1
            psize = args.get('psize') if args.get("psize") else 2
            if name:
                users_p = models.User.query.filter(models.User.name.like(f"%{name}%")).paginate(pnum,psize)
            else:
                users_p = models.User.query.paginate(pnum,psize)
            data = {
                'pnum':pnum,
                'totalPage': users_p.total,
                "users": [u.to_dict() for u in users_p.items]
            }
            return to_dict_msg(200,data,'获取用户列表成功')
        except Exception as e:
            print(e)
            return to_dict_msg(10000)

user_api.add_resource(UserList,"/user_list/")

# 登录
@user.route("/login/",methods=['POST'])
@cross_origin(supports_credentials=True)
def login():
    name = request.form.get('name')
    pwd = request.form.get('pwd')

    if not all([name,pwd]):
        return to_dict_msg(10000)
    if len(name) > 1:
        usr = models.User.query.filter_by(name = name).first()
        if usr:
            if usr.check_password(pwd):
                token = generate_auth_token(usr.id,100000000)   # 1000 1000毫秒过期
                return to_dict_msg(200,data={"token":token})
    return to_dict_msg(10011)

# 重置密码
@user.route('/reset',methods=["GET"])
def reset():
    try:
        id = int(request.args.get("id"))
        usr = models.User.query.get(id)
        usr.password = "123"
        db.session.commit()
        return to_dict_msg(200,msg = "重置密码成功")
    except Exception :
        return to_dict_msg(400)


@user.route("/test/")
@login_required
def test_login_req():
    return to_dict_msg(200)
    
